<?php

namespace App\Api;

use App\Http\Controllers\Controller;
use App\Http\Requests\StoreNoticeRequest;
use App\Http\Requests\UpdateNoticeRequest;
use App\Models\Notice;
use Illuminate\Http\Request;

class NoticeController extends Controller
{

    public function index(Request $request)
    {
        $keyword = $request->keyword;
        $state = $request->state;
        if ($state == 'true') {
            $state = 1;
        }
        if ($state == 'false') {
            $state = 0;
        }
        $notices = Notice::when($keyword, function ($query) use ($keyword) {
            $query->where('content', 'like', '%'.$keyword."%");
        })
            ->where('state', $state)->orderByDesc('id')->paginate(10);
        return $notices;
    }

    //切换发布状态
    public function toggleState(Request $request, Notice $notice)
    {
        $notice->state = !$notice->state;
        $notice->save();
        return $this->message("状态修改成功");
    }

    public function store(StoreNoticeRequest $request)
    {
        $request->validate(['content' => ['required']]);
        Notice::create($request->input());
        return $this->message("添加成功");
    }


    public function show(Notice $notice)
    {
        return $notice;
    }


    public function update(UpdateNoticeRequest $request, Notice $notice)
    {
        $request->validate(['content' => ['required']]);
        $notice->update($request->input());
        return $this->message("修改成功");
    }


    public function destroy(Notice $notice)
    {
        $notice->delete();
        return $this->message('删除成功');
    }
}
